﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObTookit.Auto
{
    public class AspxCoder:BaseCoder
    {
        public string CreateCode()
        {
            string text = ReadTemplate(Template);
            text = text.Replace("[#AUTHOR#]", Author);
            text = text.Replace("[#CREATED#]", CreateDate);

            text = text.Replace("[#ApiNS#]", AutoObj.ApiNS);
            text = text.Replace("[#ClsName#]", AutoObj.ClsName);

            text = text.Replace("[#ColumnsTh#]", CreateColumsTh());

            text = text.Replace("[#ColumnsTR#]", CreateColumnsTr());
            return text;
        }

        private string CreateColumsTh()
        {
            string colTh = "";
            foreach (FieldObject fo in FieldObjs)
            {
              colTh += "<th data-options=\"field:'"
                  + fo.Alias
                  + "',fixed:true\">"
                  + fo.Descr
                  + "</th>"
                  + CodeArgs.RN 
                  + CodeArgs.TAB3;
            }
            return colTh;
        }

        private string CreateColumnsTr()
        {
            StringBuilder colTr = new StringBuilder();
            foreach (FieldObject fo in FieldObjs)
            {
                colTr.Append(CodeArgs.SP12 + "<tr>" + CodeArgs.RN);
              colTr.Append(CodeArgs.TAB7 + "<td>" + fo.Descr + "</td>" + CodeArgs.RN);
              colTr.Append(CodeArgs.TAB8 + "<td>" + CodeArgs.RN);
              if (fo.PrimaryKey)
              {
                  colTr.Append(CodeArgs.TAB8 + "<input id=\"formAction\" name=\"formAction\" hidden=\"hidden\" />" + CodeArgs.RN);
                  colTr.Append(CodeArgs.TAB8 + "<input id=\"" + fo.Alias + "\" name=\"" + fo.Alias
                  + "\" value=\"\" style=\"border: none;\" readonly=\"readonly\" />" + CodeArgs.RN);
              }
              else if ("datetime".Equals(fo.DbType.ToLower()))
              {
                  colTr.Append(CodeArgs.TAB8 + "<input id=\"" + fo.Alias + "\" name=\"" + fo.Alias + "\" value=\"\" />" 
                      + CodeArgs.RN);
              }
              else
              {
                  colTr.Append(CodeArgs.TAB8 + "<input id=\"" + fo.Alias + "\" name=\"" + fo.Alias + "\" value=\"\" maxlength=\""+ fo.Length +"\" />" + CodeArgs.RN);
              }
              colTr.Append(CodeArgs.TAB7 + "</td>" + CodeArgs.RN);
              colTr.Append(CodeArgs.SP12 + "</tr>" + CodeArgs.RN);
            }
            return colTr.ToString();
        }
    }
}
